//
//  CXAssetManager.swift
//  RNAsmanMaster
//
//  Created by 李旭峰 on 10/22/19.
//  Copyright © 2019 Facebook. All rights reserved.
//

import UIKit
import Photos
import RxSwift
import RxCocoa

class CXAssetManager: NSObject {

    private var assetCollection_livePhotoLibrary:PHAssetCollection?
    private var albumFound_livePhotoLibrary:Bool = false
    private var photoAsset_livePhotoLibrary:PHFetchResult<AnyObject>?
    private var collection_livePhotoLibrary:PHAssetCollection?
    private var assetCollectionPlaceholder_livePhotoLibrary:PHObjectPlaceholder?
    private var albumName_livePhotoLibrary:String = "牛牛搭Pull新家工地"
    var image_livePhotoLibrary:UIImage?
  
    /// 抓拍请求回调
    private var shootCameraCompleted:((_ imgPath:String?)->())?
    /// 抓拍图片路径
    var shootImagePath:String?
    func creatAlbum(title:String,completed:((_ error:Error?)->())?){
        let fetchOptions = PHFetchOptions()
        fetchOptions.predicate = NSPredicate.init(format: "title = %@", title)
        let collection = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions)
        if let _ = collection.firstObject {
            // 相簿已存在
            completed?(nil)
        }else {
            var assetCollectionPlaceholder:PHObjectPlaceholder? = nil
            PHPhotoLibrary.shared().performChanges({
                let createAlbumRequest = PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: title)
                assetCollectionPlaceholder = createAlbumRequest.placeholderForCreatedAssetCollection
            }) { (success, error) in
                if success {
                    let collectionFetchResult = PHAssetCollection.fetchAssetCollections(withLocalIdentifiers: [assetCollectionPlaceholder!.localIdentifier], options: nil)
                    completed?(nil)
                }else{
                    completed?(error)
                }
            }
        }
    }
    func creatAlbum(_ name:String,completed:((_ album:PHAssetCollection?, _ error:Error?)->())?){
        let fetchOptions = PHFetchOptions()
        fetchOptions.predicate = NSPredicate.init(format: "title = %@", name)
        let collection = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions)
        if let album = collection.firstObject {
            // 相簿已存在
            completed?(album,nil)
        }else {
            var assetCollectionPlaceholder:PHObjectPlaceholder? = nil
            PHPhotoLibrary.shared().performChanges({
                let createAlbumRequest = PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: name)
                assetCollectionPlaceholder = createAlbumRequest.placeholderForCreatedAssetCollection
            }) { (success, error) in
                if success {
                    let collectionFetchResult = PHAssetCollection.fetchAssetCollections(withLocalIdentifiers: [assetCollectionPlaceholder!.localIdentifier], options: nil)
                    let album = collectionFetchResult.firstObject
                    completed?(album,nil)
                }else{
                    completed?(nil, error)
                }
            }
        }
    }
    private func creatAlbum(completed:((_ error:Error?)->())?) {
        let fetchOptions = PHFetchOptions()
        fetchOptions.predicate = NSPredicate.init(format: "title = %@", self.albumName_livePhotoLibrary)
        let collection = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions)
        if let _ = collection.firstObject {
            // 相簿已存在
            self.albumFound_livePhotoLibrary = true
            self.assetCollection_livePhotoLibrary = collection.firstObject
            // TODO: - 保存图片
            self.saveImage(completed: completed)
        }else {
            PHPhotoLibrary.shared().performChanges({
                let createAlbumRequest = PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: self.albumName_livePhotoLibrary)
                self.assetCollectionPlaceholder_livePhotoLibrary = createAlbumRequest.placeholderForCreatedAssetCollection
            }) { (success, error) in
                if success {
                    self.albumFound_livePhotoLibrary = true
                    let collectionFetchResult = PHAssetCollection.fetchAssetCollections(withLocalIdentifiers: [self.assetCollectionPlaceholder_livePhotoLibrary!.localIdentifier], options: nil)
                    self.assetCollection_livePhotoLibrary = collectionFetchResult.firstObject
                    // TODO: - 保存图片
                    self.saveImage(completed: completed)
                }else{
                    completed?(error)
                }
            }
        }
    }
    
    private func saveImage(completed:((_ error:Error?) -> ())?) {
        PHPhotoLibrary.shared().performChanges({
            let assetRequest = PHAssetChangeRequest.creationRequestForAsset(from: self.image_livePhotoLibrary!)
            let assetPlaceholder = assetRequest.placeholderForCreatedAsset
            let albumChangeRequest = PHAssetCollectionChangeRequest.init(for: self.assetCollection_livePhotoLibrary!)
            albumChangeRequest?.addAssets([assetPlaceholder!] as NSArray)
        }) { (success, error) in
            completed?(error)
        }
    }
    func saveImage(_ image:UIImage,completed:((_ error:Error?) -> ())?){
        self.image_livePhotoLibrary = image
        self.creatAlbum(completed: completed)
    }

    func getImageCollection(with title:String) -> PHAssetCollection? {
        let result = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .albumRegular, options: nil)
        var array:[PHAssetCollection] = []
        result.enumerateObjects { (collection, index, _) in
            array.append(collection)
        }
        for item in array {
            if item.localIdentifier == title {
                return item
            }
        }
        return nil
    }
    func saveImage(){
    }
    func downloadImage(_ path:URL, didCompleted:((Bool,UIImage?,Error?) -> ())?){
        DispatchQueue.global().async {
            do{
                let data = try Data(contentsOf: path)
                let image = UIImage(data: data)
                if let tempImage = image {
                    didCompleted?(true,tempImage,nil)
                }else{
                    let error = NSError(domain: "error", code: 100, userInfo: ["message":"数据解析异常"])
                    didCompleted?(false,nil,error)
                }
            }catch let error {
                didCompleted?(false,nil,error)
            }
        }
    }
  

}
